package com.zlf.sb.demo.juc.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

/***
 *@title OrderService
 *@description <TODO description class purpose>
 *@author wgc_j
 *@version 1.0.0
 *@create 2025-02-28 9:02
 **/
public class OrderService {
    private final ReentrantLock lock = new ReentrantLock();
    private final InventoryService inventoryService;
    private final AccountService accountService;
    private static final int quantityCount = 3;

    public OrderService(InventoryService inventoryService, AccountService accountService) {
        this.inventoryService = inventoryService;
        this.accountService = accountService;
    }

    public void processOrder(int productId, int quantity, double price) {
        lock.lock();
        try {
            if (!inventoryService.checkInventory(productId, quantity)) {
                System.out.println("库存不足");
                return;
            }
            // 扣减库存
            inventoryService.decreaseInventory(productId, quantity);
            accountService.updateBalance(1, price * quantity);
            createOrderRecord(productId, quantity, price);
        } finally {
            lock.unlock();
        }
    }

    // 库存服务
    static class InventoryService {
        public boolean checkInventory(int productId, int quantity) {
            if (quantityCount < quantity) {
                System.out.println("库存不足");
                return false;
            }
            // 实现检查库存逻辑
            System.out.println("实现检查库存逻辑productId = " + productId);
            System.out.println("实现检查库存逻辑quantity = " + quantity);
            return true;
        }

        public void decreaseInventory(int productId, int quantity) {
            // 实现扣减库存逻辑
            System.out.println("productId+ = " + productId);
            System.out.println("quantity+ = " + quantity);
        }
    }

    // 账户服务
    static class AccountService {
        public void updateBalance(int userId, double amount) {
            // 现更新账户余额逻辑
            System.out.println("现更新账户余额逻辑userId = " + userId);
            System.out.println("现更新账户余额逻辑amount = " + amount);

        }
    }

    private void createOrderRecord(int productId, int quantity, double price) {
        // 实现订单记录的创建逻辑
        System.out.println("创建订单记录：" + productId + "，数量：" + quantity + "，价格：" + price);
    }

    public static void main(String[] args) throws InterruptedException {
        OrderService.AccountService accountService1 = new OrderService.AccountService();
        OrderService.InventoryService inventoryService1 = new OrderService.InventoryService();
        OrderService orderService = new OrderService(inventoryService1, accountService1);
// 多个用户同时下单
        Thread t1 = new Thread(() -> orderService.processOrder(1, 2, 10.0));
        Thread t2 = new Thread(() -> orderService.processOrder(1, 4, 10.0));
        t1.start();
        t2.start();
        t1.join();
        t2.join();

    }

}
